<?php
require_once('wpfunctions.php');
require_once('psalmfunctions.php');
function getShortName($title,$super,$sub) {
  if(!$super && !$sub) {
    $map = mapLiturgyTable('Title','Shortname');
    $result = $map[$title];
    if(count($result) == 1) {
      return $result[0];
    }
  }
  $map = mapLiturgyTable(['Title','Date','Secondary Title'],'Shortname');
  $result = $map["$title|$super|$sub"];
  if($result) return $result[0];
  return null;
}
function mapLiturgyTable($keys,$val){
  if(is_array($keys)) {
    $key = implode('|',$keys);
  } else {
    $key = $keys;
    $keys = Array();
    $keys[] = $key;
  }
  $table = getLiturgyTable();
  $result = Array();
  foreach($table as $i => $row) {
    $curKey = Array();
    foreach($keys as $j => $aKey) {
      $curKey[] = $row[$aKey];
    }
    if(strlen(implode('',$curKey))==0){
      continue;
    }
    $curKey = implode('|',$curKey);
    if(!array_key_exists($curKey,$result)){
      $result[$curKey] = Array();
    }
    if(!in_array($row[$val], $result[$curKey])) {
      $result[$curKey][] = $row[$val];
    }
  }
  return $result;
}
function getLiturgyTable(){
  if(!file_exists(ip_masterDir("liturgy.txt"))) {
    return null;
  }
  $table = file_get_contents(ip_masterDir("liturgy.txt"));
  $strRows = explode("\n",$table);
  $rows = Array();
  $i = 0;
  $properNumberOfPipes = substr_count($strRows[0],'|');
  for($j = 0; $j<count($strRows); ++$i) {
    $curRow = $strRows[$j];
    ++$j;
    while(substr_count($curRow,'|') < $properNumberOfPipes && $j<count($strRows)) {
      $curRow .= "\n" . $strRows[$j];
      ++$j;
    }
    $rows[$i] = explode('|',$curRow);
  }
  $titles = $rows[0];
  $result = Array();
  for($i = 1; $i < count($rows); ++$i) {
    $rowResult = Array();
    $row = $rows[$i];
    foreach($titles as $j => $title) {
      $rowResult[$title] = $row[$j];
    }
    $result[] = $rowResult;
  }
  return $result;
}
?>